//
//  MineAccountViewController.m
//  YongChuanTradingArea
//
//  Created by Vivian on 2017/9/11.
//  Copyright © 2017年 李冰. All rights reserved.
//

#import "MineAccountViewController.h"
#import "MineAccountCell.h"
#import "BindPhoneViewController.h"
#import "ModifyPwdViewController.h"
#import "ApplyViewController.h"
#import "ApplyResultViewController.h"
#import "ApplyIndividualViewController.h"
#import "ApplyMemberShopViewController.h"

static NSString * const MineAccountCellID = @"MineAccountCell";

@interface MineAccountViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) UIButton *logoutBtn;
@property (nonatomic, strong) UserModel * model;

@end

@implementation MineAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的账户";
    self.model = [LBUserManage defaultManager].userModel;
    [self setupArray];
    [self createUI];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.model = [LBUserManage defaultManager].userModel;
    [self.tableView reloadData];
}

- (void)createUI{
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, lbScreenWidth, lbScreenHeight-64);
    self.tableView.rowHeight = 60;
    [self.tableView registerNib:[UINib nibWithNibName:MineAccountCellID bundle:nil] forCellReuseIdentifier:MineAccountCellID];
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 0);
    self.tableView.separatorColor = [UIColor colorWithHexString:@"#dcdcdc"];
    self.logoutBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 330, lbScreenWidth - 40, 44)];
    self.logoutBtn.centerX = self.view.centerX;
    [self.logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [self.logoutBtn setBackgroundImage:[UIImage imageNamed:@"btn_apply_3"] forState:UIControlStateNormal];
    [self.logoutBtn addTarget:self action:@selector(logoutBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.logoutBtn];
}

- (void)setupArray{
    self.titleArray = @[@"升级成为会员店或合伙人", @"头像", @"昵称", @"绑定手机", @"修改登录密码"];
}

#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:MineAccountCellID forIndexPath:indexPath];
    if (indexPath.row == 1) {
        [cell hideIcon:NO];
        for (UserModelImgList *list in _model.ImgList) {
            if ([list.imgtype isEqualToString:@"TXTP"]) {
                [cell.iconImgView sd_setImageWithURL:[NSURL URLWithString:list.image] placeholderImage:PLACE_HOLDER];
            }
        }
    }
    if (indexPath.row == 2) {
        cell.subtitleLabel.text = self.model.MEMBERNAME;

    }
    if (indexPath.row == 3) {
        if (self.model.MOBILE.length == 11) {
            cell.subtitleLabel.text = [self.model.MOBILE stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        }else{
            cell.subtitleLabel.text = self.model.MOBILE;
        }
    }
    cell.titleLabel.text = self.titleArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        UserModel * model = [LBUserManage defaultManager].userModel;
        if ([model.USERPWD isEqualToString:@"e10adc3949ba59abbe56e057f20f883e"]) {
            [UIAlertController showWithMessage:@"请先修改初始密码！" controller:self sureAction:^{
                ModifyPwdViewController * vc =  [[ModifyPwdViewController alloc] initWithNibName:@"ModifyPwdViewController" bundle:[NSBundle mainBundle]];
                [self.navigationController pushViewController:vc animated:YES];
            }];
        }else{
            if (([model.TOUSERTYPE isEqualToString:@"1"]||[model.TOUSERTYPE isEqualToString:@"0"]) && [model.USERTYPE isEqualToString:@"1"]) {
                ApplyViewController * vc = [[ApplyViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                if ([model.MEMBERSTATUS isEqualToString:@"-1"]) {
                    if ([model.TOUSERTYPE isEqualToString:@"2"]) {
                        // 注册会员店
                        ApplyMemberShopViewController * vc = [[ApplyMemberShopViewController alloc]init];
                        vc.isMember = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                    }else if ([model.TOUSERTYPE isEqualToString:@"3"]){
                        //企业合伙人
                        ApplyMemberShopViewController * vc = [[ApplyMemberShopViewController alloc]init];
                        vc.isMember = NO;
                        [self.navigationController pushViewController:vc animated:YES];
                    }else if ([model.TOUSERTYPE isEqualToString:@"4"]){
                        //注册个人合伙人
                        ApplyIndividualViewController * vc = [[ApplyIndividualViewController alloc]init];
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                    else{
                        ApplyViewController * vc = [[ApplyViewController alloc]init];
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }else if ([model.MEMBERSTATUS isEqualToString:@"3"]){
                    [UIViewController toHome];
                }else{
                    // 升级结果
                    ApplyResultViewController *vc= [[ApplyResultViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        }
    }
    if (indexPath.row == 1) {
        // 选择照片
        [self editBtnClicked];
    }
    if (indexPath.row == 2) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改昵称" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            //这里可设置对象的属性以及点击回调
            textField.placeholder = @"请输入昵称";
        }];
        
        UIAlertAction *enter = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"这里是点击enter后的回调");
            NSArray * textfields = alert.textFields;
            UITextField * namefield = textfields[0];
            [self changeName:namefield.text];
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:enter];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.row == 3) {
        BindPhoneViewController * vc =  [[BindPhoneViewController alloc] initWithNibName:@"BindPhoneViewController" bundle:[NSBundle mainBundle]];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 4) {
        ModifyPwdViewController * vc =  [[ModifyPwdViewController alloc] initWithNibName:@"ModifyPwdViewController" bundle:[NSBundle mainBundle]];
        [self.navigationController pushViewController:vc animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - request data
- (void)changeName:(NSString *)name{
    if (name.length > 0 && ![name hasSpecialString]) {
        __weak typeof(self) weakSelf = self;
        [LBNetworkingInstance requestGET:modifyPassword parameters:@{@"memberId":[LBUserManage defaultManager].user_id?:@"",@"valiteCode":@"",@"updateInfo":name?:@"",@"type":@"1"} showHUD:YES success:^(id responseObject, NSInteger code, NSString *message) {
            if (code == YCNetworkingStatusCodeSuccess){
                [LBUserManage defaultManager].userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
                weakSelf.model = [LBUserManage defaultManager].userModel;
                [MBProgressHUD showSuccess:@"修改昵称成功"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView reloadData];
                });
            }
        } failure:^(NSError *err) {
            
        }];
    }else{
        [MBProgressHUD showError:@"请输入正确的昵称！"];
    }
}

#pragma mark - btn clicked
- (void)logoutBtnAction{
    __weak typeof(self) weakSelf = self;
    [LBNetworkingInstance requestGET:logOut parameters:@{@"userId":[LBUserManage defaultManager].userModel.ID?:@""} showHUD:NO success:^(id responseObject, NSInteger code, NSString *message) {
        [weakSelf logout];
    } failure:^(NSError *err) {
        [weakSelf logout];
    }];
}

- (void)editBtnClicked{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择相片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册🌌" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeAlbum];
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机📷" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeCamera];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alert addAction:album];
    [alert addAction:camera];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - 选择照片
- (void)chosePhoto:(ChosePhotoType)type
{
    UIImagePickerController *piker = [[UIImagePickerController alloc] init];
    piker.delegate = self;
    // 设置编辑模式
    piker.allowsEditing = YES;
    
    if (type == ChosePhotoTypeAlbum) {
        piker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (type == ChosePhotoTypeCamera) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            piker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            [MBProgressHUD showError:@"相机不可用😭"];
            return;
        }
    }
    [self presentViewController:piker animated:YES completion:^{
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    __weak typeof(self) weakSelf = self;
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.1);
    NSMutableArray * array = @[].mutableCopy;
    for (UserModelImgList *list in _model.ImgList) {
        if ([list.imgtype isEqualToString:@"TXTP"]) {
            [array addObject:list.ID];
        }
    }
    NSString * delIds = @"";
    if (array.count > 0) {
        delIds = [array componentsJoinedByString:@","];
    }
    NSString * imgStr = [data base64EncodedStringWithOptions:0];
    NSDictionary * dic = @{@"baseId":[LBUserManage defaultManager].userModel.ID?:@"", @"modularName":@"memberImg", @"busType":@"TXTP", @"delIds":delIds, @"image":imgStr};
    [picker dismissViewControllerAnimated:YES completion:^{
        
        [LBNetworkingInstance requestPOST:@"http://47.92.115.33:8181/FileUpService.asmx/uploadImage" parameters:dic showHUD:YES headers:@{} progress:^(float progress) {
            
        } success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [LBUserManage defaultManager].userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
                [weakSelf.tableView reloadData];
            });
        } failure:^(NSError * _Nonnull err) {
            [MBProgressHUD showError:@"图片上传失败 请重试！"];
        }];

    }];
}

- (void)logout{
    [[LBUserManage defaultManager]logout];
    [UIViewController toLogin];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleDefault;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
